﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Taoyl.CodeTraceBLL;
using Taoyl.CodeTraceControlLib;
using Taoyl.CodeTraceHelper;
using Taoyl.CodeTraceModels;
using xbd.NodeSettings;

namespace Taoyl.CodeTracePro
{
    public partial class FrmMonitor : Form
    {
        public FrmMonitor()
        {
            InitializeComponent();

            if (Global.SysInfo!=null&&Global.SysInfo.CurrentRecord.Count>0)
            {
                this.currentRecordList = Global.SysInfo.CurrentRecord;

                foreach (var record in this.currentRecordList)
                {
                    UpdateRecord(OPEnum.Add, record);
                }
            }
        }

        private List<CodeRecord> currentRecordList = new List<CodeRecord>();
        private CodeRecordManager recordManager = new CodeRecordManager();
        private string CurrentTime { get { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); } }
        private string SysInfoPath = Application.StartupPath + "\\Config\\SysInfo.ini";

        public List<CodeRecord> GetCodeRecord()
        {
           return this.currentRecordList;
        }

        /// <summary>
        /// 数据更新
        /// </summary>
        public void UpdateMonitor()
        {
            UpdateA1A2();
            UpdateA3A4();
            UpdateA5A6();
        }

        private void UpdateA1A2()
        {
            foreach (var item in this.panel_A1A2.Controls.OfType<NoLoadStation>())
            {
                var plc = Global.A1A2.Where(c => c.DeviceName == item.JTName).FirstOrDefault();
                if (plc != null)
                {
                    if (plc.IsConnected)
                    {
                        item.JTState = (JTState)Convert.ToInt32(plc["运行状态"]);
                        item.MotorCode = plc["电机条码"]?.ToString();
                        item.NoLoadCurrent = plc["空载电流"]?.ToString();
                        item.NoLoadSpeed = plc["空载转速"]?.ToString();
                        item.AxisElongation = plc["轴伸长度"]?.ToString();
                        item.Diameter = plc["滚花直径"]?.ToString();
                    }
                    else
                    {
                        item.JTState = JTState.离线状态;
                        item.MotorCode = string.Empty;
                        item.NoLoadCurrent = "0.000";
                        item.NoLoadSpeed = "0";
                        item.AxisElongation = "0.000";
                        item.Diameter = "0.000";
                    }
                }
            }
        }

        private void UpdateA3A4()
        {
            foreach (var item in this.panel_A3A4.Controls.OfType<NoiseStation>())
            {
                var plc = Global.A3A4.Where(c => c.DeviceName == item.JTName).FirstOrDefault();
                if (plc != null)
                {
                    if (plc.IsConnected)
                    {
                        item.JTState = (JTState)Convert.ToInt32(plc["运行状态"]);
                        item.MotorCode = plc["电机条码"]?.ToString();
                        item.PositiveNoise = plc["正转噪音"]?.ToString();
                        item.NegativeNoise = plc["反转噪音"]?.ToString();
                        item.DiffNoise = plc["噪音差值"]?.ToString();
                    }
                    else
                    {
                        item.JTState = JTState.离线状态;
                        item.MotorCode = string.Empty;
                        item.PositiveNoise = "0.000";
                        item.NegativeNoise = "0.000";
                        item.DiffNoise = "0.000";

                    }
                }
            }
        }

        private void UpdateA5A6()
        {
            foreach (var item in this.panel_A5A6.Controls.OfType<LoadStation>())
            {
                var plc = Global.A5A6.Where(c => c.DeviceName == item.JTName).FirstOrDefault();
                if (plc != null)
                {
                    if (plc.IsConnected)
                    {
                        item.JTState = (JTState)Convert.ToInt32(plc["运行状态"]);
                        item.MotorCode = plc["电机条码"]?.ToString();
                        item.LoadCurrent = plc["负载电流"]?.ToString();
                        item.LoadSpeed = plc["负载转速"]?.ToString();
                    }
                    else
                    {
                        item.JTState = JTState.离线状态;
                        item.MotorCode = string.Empty;
                        item.LoadCurrent = "0.000";
                        item.LoadSpeed = "0.000";

                    }
                }
            }
        }

        public void A1A2Handle(MelsecDevice plc, string code, bool result)
        {
            if (result)
            {
                var record = this.currentRecordList.Where(c => c.MotorCode == code).FirstOrDefault();
                if (record == null)
                {
                    record = new CodeRecord()
                    {
                        MotorCode = code,
                        InsertTime = Convert.ToDateTime(CurrentTime),
                        CodeState = CodeState.空载检测OK.ToString(),
                        NoLoadCurrent = plc["空载电流"]?.ToString(),
                        NoLoadSpeed = plc["空载转速"]?.ToString(),
                        AxisElongation = plc["轴伸长度"]?.ToString(),
                        Diameter = plc["滚花直径"]?.ToString(),
                    };
                    this.currentRecordList.Add(record);

                    //更新到界面
                    UpdateRecord(OPEnum.Add, record);
                }
                else
                {
                    LogHelper.Info($"条码{code}已经扫描，请检查！");
                }
            }
            else
            {
                CodeRecord record = new CodeRecord()
                {
                    MotorCode = code,
                    InsertTime = Convert.ToDateTime(CurrentTime),
                    CodeState = CodeState.空载检测NG.ToString(),
                    NoLoadCurrent = plc["空载电流"]?.ToString(),
                    NoLoadSpeed = plc["空载转速"]?.ToString(),
                    AxisElongation = plc["轴伸长度"]?.ToString(),
                    Diameter = plc["滚花直径"]?.ToString(),
                };

                //存储到数据库
                recordManager.AddCodeRecord(record);

                //更新小时产量
                Global.ProductCompletedHandle?.Invoke(false);
            }
        }

        public void A3A4Handle(SiemensDevice plc, string code, bool result)
        {
            var record = this.currentRecordList.Where(c => c.MotorCode == code).FirstOrDefault();
            if (record != null)
            {
                if (result)
                {
                    record.PositiveNoise = plc["正转噪音"]?.ToString();
                    record.NegativeNoise = plc["反转噪音"]?.ToString();
                    record.NoiseDiff = plc["噪音差值"]?.ToString();
                    record.InsertTime = Convert.ToDateTime(CurrentTime);
                    record.CodeState = CodeState.噪音检测OK.ToString();

                    this.UpdateRecord(OPEnum.Modify, record);
                }
                else
                {
                    record.PositiveNoise = plc["正转噪音"]?.ToString();
                    record.NegativeNoise = plc["反转噪音"]?.ToString();
                    record.NoiseDiff = plc["噪音差值"]?.ToString();
                    record.InsertTime = Convert.ToDateTime(CurrentTime);
                    record.CodeState = CodeState.噪音检测NG.ToString();

                    //存储到数据库
                    recordManager.AddCodeRecord(record);
                    //更新小时产量
                    Global.ProductCompletedHandle?.Invoke(false);

                    //从集合中移除
                    this.currentRecordList.Remove(record);

                    //更新界面
                    this.UpdateRecord(OPEnum.Delete, record);

                }
            }
            else
            {
                LogHelper.Info($"条码{code}还未扫描，请检查！");
            }
        }

        public void A5A6Handle(ModbusTCPDevice plc, string code, bool result)
        {
            var record = this.currentRecordList.Where(c => c.MotorCode == code).FirstOrDefault();
            if (record != null)
            {
                if (result)
                {
                    record.LoadCurrent = plc["负载电流"]?.ToString();
                    record.LoadSpeed = plc["负载转速"]?.ToString();
                    record.InsertTime = Convert.ToDateTime(CurrentTime);
                    record.CodeState = CodeState.负载检测OK.ToString();
                    record.MeasureResult = "OK";

                }
                else
                {
                    record.LoadCurrent = plc["负载电流"]?.ToString();
                    record.LoadSpeed = plc["负载转速"]?.ToString();
                    record.InsertTime = Convert.ToDateTime(CurrentTime);
                    record.CodeState = CodeState.负载检测NG.ToString();
                }
                //存储到数据库
                recordManager.AddCodeRecord(record);
                //更新小时产量
                Global.ProductCompletedHandle?.Invoke(result);

                //从集合中移除
                this.currentRecordList.Remove(record);

                //更新界面
                this.UpdateRecord(OPEnum.Delete, record);

            }
            else
            {
                LogHelper.Info($"条码{code}还未扫描，请检查！");
            }
        }

        /// <summary>
        /// 更新处理
        /// </summary>
        /// <param name="opCode"></param>
        /// <param name="record"></param>
        private void UpdateRecord(OPEnum opCode, CodeRecord record)
        {
            if (this.dgv_Record.InvokeRequired)
            {
                this.dgv_Record.Invoke(new Action<OPEnum, CodeRecord>(UpdateRecord), opCode, record);
            }
            else
            {
                switch (opCode)
                {
                    case OPEnum.Add:
                        int index = this.dgv_Record.Rows.Add();
                        this.dgv_Record.Rows[index].Cells[0].Value = record.InsertTime.ToString("yyyy-MM-dd HH:mm:ss");
                        this.dgv_Record.Rows[index].Cells[1].Value = record.MotorCode;
                        this.dgv_Record.Rows[index].Cells[2].Value = record.CodeState;
                        this.dgv_Record.Rows[index].Cells[3].Value = record.NoLoadCurrent;
                        this.dgv_Record.Rows[index].Cells[4].Value = record.NoLoadSpeed;
                        this.dgv_Record.Rows[index].Cells[5].Value = record.AxisElongation;
                        this.dgv_Record.Rows[index].Cells[6].Value = record.Diameter;
                        this.dgv_Record.Rows[index].Cells[7].Value = record.PositiveNoise;
                        this.dgv_Record.Rows[index].Cells[8].Value = record.NegativeNoise;
                        this.dgv_Record.Rows[index].Cells[9].Value = record.NoiseDiff;
                        this.dgv_Record.Rows[index].Cells[10].Value = record.LoadCurrent;
                        this.dgv_Record.Rows[index].Cells[11].Value = record.LoadSpeed;


                        break;
                    case OPEnum.Modify:
                        foreach (DataGridViewRow item in this.dgv_Record.Rows)
                        {
                            if (item.Cells[1].Value.ToString() == record.MotorCode)
                            {
                                item.Cells[0].Value = record.InsertTime.ToString("yyyy-MM-dd HH:mm:ss");
                                item.Cells[1].Value = record.MotorCode;
                                item.Cells[2].Value = record.CodeState;
                                item.Cells[3].Value = record.NoLoadCurrent;
                                item.Cells[4].Value = record.NoLoadSpeed;
                                item.Cells[5].Value = record.AxisElongation;
                                item.Cells[6].Value = record.Diameter;
                                item.Cells[7].Value = record.PositiveNoise;
                                item.Cells[8].Value = record.NegativeNoise;
                                item.Cells[9].Value = record.NoiseDiff;
                                item.Cells[10].Value = record.LoadCurrent;
                                item.Cells[11].Value = record.LoadSpeed;
                                break;
                            }
                        }
                        break;
                    case OPEnum.Delete:
                        foreach (DataGridViewRow item in this.dgv_Record.Rows)
                        {
                            if (item.Cells[1].Value.ToString() == record.MotorCode)
                            {
                                this.dgv_Record.Rows.Remove(item);
                                break;
                            }
                        }
                        break;
                    default:
                        break;
                }
            }

            //每次更新保存本地文件
            //如果为了防止软件异常关闭，可以添加此操作
            Global.SysInfo.CurrentRecord = this.currentRecordList;
            SysInfoManager.SaveSysInfo(Global.SysInfo, this.SysInfoPath);
        }

        private void dgv_Record_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            DataGridViewHelper.DgvRowPostPaint(this.dgv_Record, e);
        }
    }
}
